package ag.script.project.standard.img;

import ag.script.project.standard.core.ScreensDes;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * 缩放图片是根据屏幕宽度来缩放的，无论是哪种脚本，都按照屏幕宽度来缩放
 */
public class ImgScale {

    /**
     * 缩放图片
     *
     * @param file_project  项目路径:D:\\MyWorkspace\\Java\\ag-app-res\\ag-apps\\czymf
     * @param imgPath       图片路径:D:\\MyWorkspace\\Java\\ag-app-res\\ag-apps\\czymf\\res\\imgs\\w1080p\\创造与魔法.png
     * @param devScreenDes  开发环境的屏幕的宽:1080x
     * @param destScreenDes 目标屏幕的宽:720x
     */
    public static boolean scale(File file_project, String imgPath, ScreensDes devScreenDes, ScreensDes destScreenDes) {
        try {
            File file_res = new File(file_project, "res");
            File file_img = new File(file_res, "img");

            //根据屏幕宽度大小来进行适配图片:并且写入到对应的文件夹当中
            if (FileUtil.exist(imgPath) && StrUtil.endWithAnyIgnoreCase(FileUtil.extName(imgPath), "png", "jpg", "jpeg")) {
                if (destScreenDes.getW() == devScreenDes.getW()) {
                    float scaleBl = (float) destScreenDes.getW() / devScreenDes.getW();
                    BufferedImage bufferedImage = ImgUtil.read(imgPath);
                    Image scale = ImgUtil.scale(bufferedImage, scaleBl);
                    File img_screen_mkdir = new File(file_img, destScreenDes.getName());//project/res/img/720x
                    File img_output_file = new File(img_screen_mkdir, FileUtil.getName(imgPath));//project/res/img/720x/创造与魔法.png
                    ImgUtil.write(scale, img_output_file);
                } else {
                    BufferedImage bufferedImage = ImgUtil.read(imgPath);
                    File img_screen_mkdir = new File(file_img, destScreenDes.getName());//project/res/img/720x
                    File img_output_file = new File(img_screen_mkdir, FileUtil.getName(imgPath));//project/res/img/720x/创造与魔法.png
                    ImgUtil.write(bufferedImage, img_output_file);
                }
            }
            return true;
        } catch (Throwable err) {
            return false;
        }

    }
}
